<template>
  <div class="app-container">
    <div style="background: #f2f2f2; max-width: 800px; padding: 10px 20px">
      <el-form style="width: 100%" :model="queryParams" ref="queryRef">
        <el-form-item label="硅基流动">
          <div class="_reset">
            <el-switch
              size="large"
              v-model="queryParams.status"
              :active-value="1"
              :inactive-value="0"
            />
          </div>
        </el-form-item>
        <el-divider />
        <el-form-item label="API密钥" label-position="top">
          <div class="_reset">
            <el-input
              v-model="queryParams.apiKey"
              style="width: 100%"
              type="password"
              placeholder="请输入"
              show-password
            />
            <el-button @click="handleOpenCheck">检查</el-button>
          </div>
        </el-form-item>
        <el-form-item label="API地址" label-position="top">
          <el-input v-model="queryParams.apiUrl" style="width: 100%" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="模型" label-position="top">
          <div class="model_box">
            <div truncated>{{ queryParams.name }} </div>
            <el-divider />
            <el-scrollbar height="400px" style="width: 100%">
              <div v-for="item in queryParams.aiModelConfigs" :key="item.id" class="_modelList">
                <div truncated style="margin: 0 20px 0 10px">{{ item.name }} </div>
                <el-popover placement="right" trigger="click">
                  <template #reference>
                    <el-link>
                      <el-icon :size="20">
                        <Tools />
                      </el-icon>
                    </el-link>
                  </template>
                  <el-checkbox-group
                    v-model="citiesList"
                    @change="handleSelectionChange(item, citiesList)"
                    size="small"
                  >
                    <el-checkbox
                      v-for="i in handleModelSelectionList(item)"
                      :key="i.key"
                      :label="i.label"
                      :value="`1/${i.key}`"
                      checked
                    />
                  </el-checkbox-group>
                </el-popover>

                <el-link class="_delete" @click="handleDelete(item.name)">
                  <el-icon :size="20" color="red">
                    <Remove />
                  </el-icon>
                </el-link>
              </div>
            </el-scrollbar>
          </div>
        </el-form-item>
        <el-form-item label="">
          <el-button :icon="EditPen" @click="handleOpenModel()">管理</el-button>
          <el-button @click="handleAddModel()">保存</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog v-model="checkVisible" title="请选择要检测的模型" align-center width="400">
      <el-select
        v-model="checkVal"
        style="width: 300px"
        clearable
        fit-input-width
        filterable
        placeholder="请选择"
      >
        <el-option
          v-for="item in queryParams.aiModelConfigs"
          :key="item.name"
          :label="item.name"
          :value="item.name"
        ></el-option>
      </el-select>

      <template #footer>
        <el-button @click="checkVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCheck()">确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="modelVisible" title="硅基流动模型" align-center width="800">
      <el-input
        v-model="searchUrl"
        style="width: 100%"
        placeholder="搜索模型名称"
        @keyup.enter="getModelList()"
      >
        <template #append>
          <el-button :icon="Search" @click="getModelList()" />
        </template>
      </el-input>

      <div class="model_box" style="margin-top: 10px">
        <div truncated style="color: #999">{{ queryParams.name }} </div>
        <el-scrollbar height="400px" style="width: 100%">
          <div v-for="(item, index) in dialogModelList" :key="item.name" class="_modelList">
            <div truncated style="margin: 0 20px 0 10px">{{ item.name }} </div>
            <el-button
              class="_delete"
              :icon="item.type ? Minus : Plus"
              :type="item.type ? '' : 'primary'"
              @click="handleModeEdit(item.name, !item.type)"
            />
          </div>
        </el-scrollbar>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { EditPen, Search, Minus, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {
  getModelDetailsApi,
  postModelAddOrEditApi,
  postModelBtnListApi,
  postModelCheckApi
} from '@/api/ai/management'

import useAiStore from '@/store/modules/ai'

const aiStore = useAiStore()
const queryParams = reactive({
  id: null,
  name: null,
  type: null,
  status: null,
  apiKey: null,
  apiUrl: null,
  aiModelConfigs: []
})
const checkVisible = ref(false)
const checkVal = ref(null)
const citiesList = ref([`1/推理}`])
const modelVisible = ref(false)
const searchUrl = ref(null)
const dialogModelList = ref([])
function handleCheck() {
  checkVisible.value = false
  postModelCheckApi(queryParams).then((res) => {
    ElMessage({
      message: res.code === 200 ? '连接成功' : '连接失败',
      type: res.code === 200 ? 'success' : 'warning'
    })
  })
}
function handleOpenCheck() {
  checkVisible.value = true
}
function handleDelete(name) {
  const _index = queryParams.aiModelConfigs.findIndex((item) => item.name === name)
  queryParams.aiModelConfigs.splice(_index, 1)
  handleAddModel()
}

/**处理模型选择列表 */
function handleModelSelectionList(item) {
  return [{ value: 1, label: '推理', key: 'includeReasoning' }]
}
const isChange = ref(false)
/**选择类型发生变化 */
function handleSelectionChange(i, list) {
  isChange.value = true
  // console.log(i, list)
  const selectedOptions = list.map((e) => {
    const [valuePart, labelPart] = e.split('/')
    return { value: valuePart, label: labelPart }
  })
  console.log(selectedOptions)
  queryParams.aiModelConfigs.forEach((e) => {
    if (e.id === i.id) {
      e.includeImage = +selectedOptions.find((item) => item?.label === 'includeImage')?.value
      e.includeEmbedding = +selectedOptions.find((item) => item?.label === 'includeEmbedding')
        ?.value
      e.includeReasoning = +selectedOptions.find((item) => item?.label === 'includeReasoning')
        ?.value
    }
  })
  console.log(queryParams.aiModelConfigs)
  postModelAddOrEditApi(queryParams)
}
/**添加模型 */
function handleAddModel() {
  if (!isChange.value) {
    queryParams.aiModelConfigs.forEach((e) => {
      e.includeReasoning = 1
    })
  }
  postModelAddOrEditApi(queryParams).then((res) => {
    console.log('添加成功')
    if (res.code === 200) {
      ElMessage({
        message: '修改成功',
        type: 'success'
      })
    }
    getList()
  })
}
/**打开管理的模型列表 */
function handleOpenModel() {
  modelVisible.value = true
  getModelList()
}
/**获取模型列表 */
function getModelList() {
  postModelBtnListApi({
    ...queryParams,
    aiModelConfigs: searchUrl.value ? [{ name: searchUrl.value }] : []
  }).then((res) => {
    let list = res?.data
    // 初始化所有对象的 type 属性为 false
    list.forEach((j) => {
      j['type'] = false
    })
    // 遍历 queryParams.aiModelConfigs 并设置匹配对象的 type 属性为 true
    queryParams.aiModelConfigs.forEach((i) => {
      const matchingItem = list.find((j) => j.id === i.id)
      if (matchingItem) {
        matchingItem['type'] = true
      }
    })
    dialogModelList.value = list
  })
}

/**模型选择 */
function handleModeEdit(name, type) {
  // console.log(name, type)
  const _item = dialogModelList.value.find((i) => i.name === name)
  if (type) {
    _item.type = type
    queryParams.aiModelConfigs.push(_item)
  } else {
    _item.type = type
    const _index = queryParams.aiModelConfigs.findIndex((i) => i.name === name)
    queryParams.aiModelConfigs.splice(_index, 1)
  }
}
function getList() {
  getModelDetailsApi().then((res) => {
    Object.keys(queryParams).forEach((key) => {
      queryParams[key] = res?.data[key]
    })
    aiStore.setAiInfo(queryParams)
  })
}

getList()
</script>
<style lang="scss" scoped>
._reset {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: end;
}

.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  width: 100%;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}
.model_box {
  background: #fff;
  width: 100%;
  padding: 10px;
  border-radius: 5px;
  border: 1px solid #ebeef5;
  ::v-deep .el-divider--horizontal {
    margin: 0 0 10px;
  }
  ._modelList {
    position: relative;
    display: flex;
    align-items: center;
    min-height: 30px;
    margin-bottom: 10px;
    ._delete {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }
}
</style>
